from commands.core.command import Command
from src.content_manager import ContentManager
from src.vobjects.video import Video
from src.utils import get_video_url

from invidious import Invidious

class DownloadCmd(Command):

    def __init__(self):
        self.names = ["download", "dw"]
        self.has_args = True

        self.iv = Invidious()
    
    def download(self, item, only_audio=False):
        if not type(item.parent) in [Video]: return "Error: Incorrect item type!"

        parent = item.parent
        url = get_video_url(parent, self.iv.get_working_mirror())

        title = parent.title

        ContentManager.download(title, url, only_audio=only_audio)
   
    def check_args(self, args: list):
        if len(args) > 0:
            arg = args[0]
            if arg == "-a": return None
            else: return "Error: Incorrect arguments"
        else: return None

    def check_only_audio(self, args: list):
        return True if len(args) > 0 and args[0] == "-a" else False

    def execute(self, args: list, obj):
        check = self.check_args(args)
        if not check is None: return check 

        only_audio = self.check_only_audio(args)

        item, _ = obj.get_selected()

        if type(item) is list: 
            for it in item:
                self.download(it, only_audio)
        else: self.download(item, only_audio)

